package cn.jhc.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.jhc.bean.RoleRight;
import cn.jhc.bean.User;
import cn.jhc.factory.ConnectionFactory;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class RoleRightDAO {
	public static List<RoleRight> getGroups(){
		List<RoleRight> list = new ArrayList<RoleRight>();
		Connection cnn = (Connection) ConnectionFactory.getConnection();
		ResultSet rs = null;
		Statement statement = null;
		
		String sql = "select id,roleid,userId from role_right";
		try {
			statement = (Statement) cnn.createStatement();
			rs = statement.executeQuery(sql);
		while(rs.next()){
			int id = rs.getInt(1);
			int roleid = rs.getInt(2);
			int userId = rs.getInt(3);
			RoleRight right = new RoleRight(id, roleid, userId);
			list.add(right);
		}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				statement.close();
				cnn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}
	
	public boolean addRoleRight(RoleRight right){
		Statement stat = null;
		boolean action = true;
		Connection conn = (Connection) ConnectionFactory.getConnection();
		
		String sql = "insert into role_right(roleid,userId) values("+right.getRoleid()+","+right.getUserId()+")";
		
		try
		{
			stat = (Statement) conn.createStatement();
			stat.execute(sql);
		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				stat.close();
				conn.close();
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return action;
	}
	
	public int findIdByName(String name)
	{
		Statement stat = null;
		ResultSet resultSet = null;
		int value = 0;
		Connection conn = (Connection) ConnectionFactory.getConnection();
		
		String sql = "select roleid from role_right where userId=(select userId from userinfo where loginname='"+name+"')";
		try
		{
			stat = (Statement) conn.createStatement();
			resultSet = stat.executeQuery(sql);
			if(resultSet.first())
			{
				value = resultSet.getInt(1);
			}
			else
			{
				value = 0;
			}
		} catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			try
			{
				stat.close();
				conn.close();
			} catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return value;
	}
}
